package com.imooc.mail.interceptor;

import com.imooc.mail.consts.MallConst;
import com.imooc.mail.exception.UserLoginException;
import com.imooc.mail.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author wjc
 * Date on 2020/6/6 12:50
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    /**
     * true 表示继续流程 false 表示中断
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("UserLoginInterceptor ---> preHandler...");
        User user = (User) request.getSession().getAttribute(MallConst.CURRENT_USER);
        if (Objects.isNull(user)){
            log.info("user is null");
            // 1. response.getWriter().print("error) 但是不推荐，因为已经写好了返回封装为什么还要序列化？不够优雅
            // 2. 用统一异常处理
            throw new UserLoginException();
//            return false;
        }
        return true;
    }
}
